package com.gary.demo.biz.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gary.demo.biz.CustomerBO;
import com.gary.demo.common.model.LoginHolder;
import com.gary.demo.common.utils.CheckUtil;
import com.gary.demo.dao.CustomerMapper;
import com.gary.demo.entity.Customer;
import com.gary.demo.model.param.CustomerOperateParam;
import com.gary.demo.model.param.CustomerQueryParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CustomerBOImpl implements CustomerBO {

    @Autowired
    private LoginHolder loginHolder;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public void add(CustomerOperateParam param) {
        Customer customer = new Customer();
        BeanUtils.copyProperties(param, customer);
        customer.setCreator(loginHolder.currentUser().getUserName());
        customerMapper.insert(customer);
    }

    @Override
    public void update(CustomerOperateParam param) {
        Customer cus = customerMapper.selectById(param.getId());
        CheckUtil.isNull(cus, "未查询到对应的用户信息");
        Customer customer = new Customer();
        BeanUtils.copyProperties(cus, customer);
        customer.setModifier(loginHolder.currentUser().getUserName());
        customerMapper.updateById(customer);

    }

    @Override
    public IPage<Customer> pageQuery(CustomerQueryParam param) {
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(param.getCreator())) {
            queryWrapper.eq(Customer::getCreator, param.getCreator());
        }
        if (StrUtil.isNotBlank(param.getName())) {
            queryWrapper.like(Customer::getName, param.getName());
        }
        if (StrUtil.isNotBlank(param.getPhone())) {
            queryWrapper.like(Customer::getName, param.getPhone());
        }
        IPage<Customer> page = new Page<>(param.getPageNum(), param.getPageSize());

        return customerMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Customer> list(String name) {
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like(Customer::getName, name);
        }
        List<Customer> customers = customerMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(customers)) {
            return Lists.newArrayList();
        }
        return customers;
    }
}
